package 链表;

/**
 * @author 陈艺博
 * @date 2021-02-17 21:11
 * @description https://leetcode-cn.com/problems/reverse-linked-list/
 **/
public class _206_reverse_linked_list_反转链表 {

//    // 递归形式
//    public ListNode reverseList(ListNode head) {
//        //不需要反转
//        if (head == null || head.next == null) {
//            return head;
//        }
//        //递归方法
//        ListNode newHead = reverseList(head.next);
//        //后一个指向前一个
//        head.next.next=head;
//        //最后一个指向null
//        head.next = null;
//        return newHead;
//    }

    public ListNode reverseList(ListNode head) {
        //不需要反转
        if (head == null || head.next == null) {
            return head;
        }

        ListNode newHead = null;
        while (head != null) {
            ListNode tmp = head.next;
            head.next = newHead;
            newHead = head;
            head = tmp;
        }
        return newHead;
    }

    public static void main(String[] args) {
        ListNode node = new ListNode(5);
        ListNode firstNode = new ListNode(6, node);
        System.out.println(firstNode);
        System.out.println(new _206_reverse_linked_list_反转链表().reverseList(firstNode));
    }
}
